let { list, tab, userList } = require('./mock')
const bodyParser = require('body-parser')
const JWT = require('jsonwebtoken')
const key = 'erbfwdwqqweqweq'
// TypeScript
const AlipaySdk = require('alipay-sdk').default;
const AlipayFormData = require('alipay-sdk/lib/form').default;

// 普通公钥模式
const alipaySdk = new AlipaySdk({
	appId: '',
	privateKey: ``,
	gateway: ''
});


module.exports = app => {
	app.use(bodyParser.json())
	// 首页列表
	app.get('/api/list', (req, res) => {
		const { pageSize = 10, pageCode = 1, value } = req.query;
		if (value) {
			const newList = list.filter(v => {
				const { body: { items: [item] } } = v
				const { label_title, id, product_price, product_name, url } = item
				console.log(label_title, value)
				console.log(product_name, value)
				return label_title.includes(value) || product_name.includes(value)
			})

			res.send({
				code: 200,
				data: {
					data: newList.map(v => {
						const { body: { items: [item] } } = v
						const { label_title, id, product_price, product_name, url } = item
						return {
							id,
							image: url,
							title: product_name,
							word: label_title,
							price: product_price
						}
					}),
					total: newList.length,
				},
				message: '数据获取成功'
			})


		} else {
			if (pageSize * pageCode <= list.length) {
				res.send({
					code: 200,
					data: {
						data: list.slice((pageCode - 1) * pageSize, pageCode * pageSize).map(v => {
							const { body: { items: [item] } } = v
							const { label_title, id, product_price, product_name, url } = item
							return {
								id,
								image: url,
								title: product_name,
								word: label_title,
								price: product_price
							}
						}),
						total: list.length,
					},
					message: '数据获取成功'
				})
			} else {
				res.send({
					code: 204,
					message: '没有更多数据了'
				})
			}
		}

	})
	// 分类列表
	app.get('/api/tab', (req, res) => {
		res.send({
			code: 200,
			data: tab,
			message: '数据获取成功'
		})
	})
	// 登录接口
	app.post('/api/login', (req, res) => {
		const { username, password } = req.body;
		const user = userList.find(v => v.username === username && v.password === password);
		if (user) {
			res.send({
				code: 200,
				message: '登录成功， 欢迎' + user.nickname,
				data: {
					token: JWT.sign({
						username: user.username,
						nickname: user.nickname,
						avator: user.avator,
						id: user.id
					}, key),
					username: user.username,
					nickname: user.nickname,
					addressList: user.addressList,
					orderList: user.orderList,
					avator: user.avator,
					id: user.id
				}
			})
		} else {
			res.send({
				code: 403,
				message: '账户密码错误， 请重新登录',
			})
		}
	})

	// 创建订单接口
	app.post('/api/order/list', (req, res) => {
		const { token } = req.headers;
		const { data } = req.body;
		try {
			const { id } = JWT.verify(token, key);
			const item = userList.find(v => v.id === id)
			item.orderList.unshift(data);
			res.send({
				code: 200,
				message: '创建订单成功'
			})
		} catch {
			res.send({
				code: 400,
				message: '订单创建失败'
			})
		}
	})

	// 下单支付接口
	app.post('/api/pay', async (req, res) => {
		const { id, price, title } = req.body;
		// 调用支付接口

		const formData = new AlipayFormData();
		// 调用 setMethod 并传入 get，会返回可以跳转到支付页面的 url
		formData.setMethod('get');

		formData.addField('returnUrl', 'http://localhost:3000/pay/result');
		// get method 需要确保 field 都是字符串
		formData.addField('bizContent', JSON.stringify({
			outTradeNo: id,
			totalAmount: price,
			subject: title,
		}));

		try {
			const result = await alipaySdk.exec(
				'alipay.trade.wap.pay',
				{},
				{ formData: formData },
			);

			res.send({
				code: 200,
				data: result
			})
		} catch (error) {
			res.send({
				code: 400,
				data: error
			})
		}
	})

	// 查询接口
	app.get('/api/order/query', async (req, res) => {
		const { out_trade_no, trade_no } = req.query
		const { token } = req.headers
		try {
			const { id } = JWT.verify(token, key);
			try {
				const result = await alipaySdk.exec(
					'alipay.trade.query',
					{
						bizContent: {
							out_trade_no, trade_no
						},
					}
				);
				const { code, tradeStatus } = result;
				if (code === '10000') {
					switch (tradeStatus) {
						case 'WAIT_BUYER_PAY':
							res.send({
								code: 200,
								message: '交易创建，等待买家付',
								data: result
							});
							return
						case 'TRADE_CLOSED':
							res.send({
								code: 200,
								message: '未付款交易超时关闭，或支付完成后全额退款',
								data: result
							});
							return
						case 'TRADE_SUCCESS':
							const item = userList.find(v => v.id === id)
							const v = item.orderList.find(v => v.id === out_trade_no)
							v.state = '待收货'

							res.send({
								code: 200,
								message: '交易支付成功',
								data: result
							});
							return
						case 'TRADE_FINISHED':
							res.send({
								code: 200,
								message: '交易结束，不可退款',
								data: result
							});
							return
					}
				} else if (code === '40004') {
					res.send({
						code: 404,
						message: '交易不存在'
					})
				}
			} catch (error) {
				res.send({
					message: '查询失败， 订单不存在',
					error
				})
			}
		} catch {
			res.send({
				code: 403,
				message: 'token 非法'
			})
		}

	})

	// 地址删除接口
	app.delete('/api/address/list', async (req, res) => {
		const { id } = req.query;
		const { token } = req.headers
		try {
			const { id: userID } = JWT.verify(token, key);
			try {
				const item = userList.find(v => v.id === userID)

				if (item) {
					const i = item.addressList.find(v => v.id === id)
					item.addressList.splice(i, 1)
					res.send({
						code: 200,
						message: '删除成功'
					})
				} else{
					res.send({
						code: 404,
						message: '未找到删除的数据'
					})
				}
			} catch (error) {
				res.send({
					message: '查询失败',
					error
				})
			}
		} catch {
			res.send({
				code: 403,
				message: 'token 非法'
			})
		}
	})
}